package com.citcc.api.config;

import com.citcc.business.bean.CdzAppUser;
import com.citcc.business.service.CdzAppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 * User: qinbo
 * Date: 2019/4/5
 * Time: 19:03
 * Description:
 */
@Component
public class UserLoginHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Resource
    private CdzAppUserService cdzAppUserService;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().isAssignableFrom(CdzAppUser.class) && methodParameter.hasParameterAnnotation(Authorization.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest request, WebDataBinderFactory webDataBinderFactory) {
        //获取用户ID
        try {
            Object object = request.getAttribute("phone", RequestAttributes.SCOPE_REQUEST);

            if(object == null){
                return null;
            }
            System.out.println("初始化"+(String) object);
            //获取用户信息
            //UserEntity user = userService.queryObject((Long)object);
            CdzAppUser user = cdzAppUserService.getAppUserByPhone((String) object);
            return user;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}